package command

import (
	"fmt"
	"time"

	"github.com/pkg/errors"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"

	bkev1beta1 "gopkg.openfuyao.cn/cluster-api-provider-bke/api/v1beta1"
)

type Bootstrap struct {
	BaseCommand

	Node      *confv1beta1.Node
	BKEConfig string
	Phase     confv1beta1.BKEClusterPhase
}

func (b *Bootstrap) Validate() error {

	if b.Phase == "" {
		return errors.New("phase is empty")
	}
	if b.BKEConfig == "" {
		return errors.New("bkeConfig is empty")
	}
	return b.BaseCommand.validate()
}

func (b *Bootstrap) New() error {
	if err := b.Validate(); err != nil {
		return err
	}
	commandName := fmt.Sprintf("%s%s-%d", BootstrapCommandNamePrefix, b.Node.IP, time.Now().Unix())
	bkeConfig := fmt.Sprintf("bkeConfig=%s:%s", b.NameSpace, b.BKEConfig)
	phase := fmt.Sprintf("phase=%s", b.Phase)

	customLabel := ""
	switch b.Phase {
	case bkev1beta1.InitControlPlane:
		customLabel = MasterInitCommandLabel
	case bkev1beta1.JoinControlPlane:
		customLabel = MasterJoinCommandLabel
	case bkev1beta1.JoinWorker:
		customLabel = WorkerJoinCommandLabel
	}

	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: "check container runtime",
			Command: []string{
				"K8sEnvInit",
				"init=false",
				"check=true",
				"scope=runtime",
				bkeConfig,
			},
			Type:          agentv1beta1.CommandBuiltIn,
			BackoffDelay:  3,
			BackoffIgnore: false,
		},
		{
			ID: "bootstrap",
			Command: []string{
				"Kubeadm",
				phase,
				bkeConfig,
			},
			Type:          agentv1beta1.CommandBuiltIn,
			BackoffDelay:  3,
			BackoffIgnore: false,
		},
	}
	commandSpec.TTLSecondsAfterFinished = 0

	//commandSpec.NodeName = b.Node.Hostname

	nodes := bkenode.Nodes{*b.Node}
	commandSpec.NodeSelector = getNodeSelector(nodes)

	return b.newCommand(commandName, BKEMachineLabel, commandSpec, customLabel)

}
